import { message } from 'antd';
import { getMcontractByIDService } from '../services';
import { useEffect } from 'react';
import { getKeyRouter } from '@/utils';
import { history } from 'umi';

const getPidContractInfo = (handleOldInfo: (info: Record<string, any>) => void, currentInfo: Record<string, any>) => {
  /** 详情回调 */
  const detailsCallback = (res: any) => {
    if (res && res?.msgFlag) {
      handleOldInfo(res?.obj);
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取详情 */
  const { getMcontractByIDRun, getMcontractByIDLoading } = getMcontractByIDService(detailsCallback);

  useEffect(() => {
    if (currentInfo?.pID && currentInfo?.oldModifyType) {
      getMcontractByIDRun({
        id: currentInfo?.pID,
      });
    }
  }, [currentInfo?.pID, currentInfo?.oldModifyType]);

  return {
    oldContractLoading: getMcontractByIDLoading,
  };
};

const editModifyContract = (currentInfo: Record<string, any>, setReload: (resObj: Record<string, any>) => void) => {
  /** 详情回调 */
  const detailsCallback = (res: any) => {
    if (res && res?.msgFlag) {
      const detailInfo: Record<string, any> = res?.obj;

      const payload: Record<string, any> = {
        pIDDetailInfo: detailInfo,
        pageType: currentInfo?.changeWay == 0 ? 'modify' : currentInfo?.changeWay == 1 ? 'break' : null,
        id: currentInfo?.pID ? currentInfo?.id : null,
        pID: currentInfo?.pID,
        returnPathName: '/contractController/performManage',
      };

      let pageRouterUrl: string = '';
      if (payload?.pageType == 'modify') {
        pageRouterUrl = '/contractController/modifyRouter';
      } else if (payload?.pageType == 'break') {
        pageRouterUrl = '/contractController/breakRouter';
      }
      history.push({
        pathname: `${pageRouterUrl}/:${getKeyRouter()}${getKeyRouter()}`,
        state: {
          ...payload,
        },
      });

      setReload({});
    } else {
      message.error(res?.msg);
    }
  };

  /** 获取详情 */
  const { getMcontractByIDRun } = getMcontractByIDService(detailsCallback);

  useEffect(() => {
    if (currentInfo?.clickModify && (currentInfo?.pID || currentInfo?.id)) {
      getMcontractByIDRun({
        id: currentInfo?.pID ? currentInfo?.pID : currentInfo?.id,
      });
    }
  }, [currentInfo?.pID, currentInfo?.id]);
};

export { getPidContractInfo, editModifyContract };
